var socket = socket || (function () {

    var connected = false;
    var websocket;

    function initSocket (options) {
        //服务器地址
        var locate = window.location;
        var url = options.url ? options.url : "ws://" + locate.hostname + ":" + locate.port + "/websocket";
        //回调函数
        var callback = options.callback;
        if (typeof callback !== "function") {
            console.log('callback 必须为函数');
            return false;
        }
        //判断当前浏览器是否支持WebSocket
        try {
            websocket = new ReconnectingWebSocket(url);
            //连接发生错误的回调方法
            websocket.onerror = function () {
                showMessage("error");
                connected = false;
                reconnect();
            };

            //连接成功建立的回调方法
            websocket.onopen = function (event) {
                //showMessage("open");
            };

            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                showMessage(event.data);
            };

            //连接关闭的回调方法
            websocket.onclose = function () {
                //showMessage("close");
            };

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close();
            };
            return callback();
        } catch (e) {
            reconnect();
        }
    }

    function reconnect () {
        if (connected) return;
        connected = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
            init({});
            connected = false;
        }, 2000);
    }

    //将消息显示在网页上
    function showMessage (message) {
        console.log(message);
        localStorage.setItem("heartbeat", message);
    }

    //关闭连接
    function closeWebSocket () {
        websocket.close();
    }

    function send (message) {
        localStorage.setItem("heartbeat", "");
        websocket.send(message);
    }

    return {
        initSocket: initSocket
        , send: send
        , showMessage: showMessage
        , closeWebSocket: closeWebSocket
    };

})();
socket.initSocket({
    callback: function () {
        setInterval(function () {
            socket.send('欢迎使用瑞健医信产品');
        }, 1000)
    }
});